package com.insyte.fragments;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.insyte.R;
import com.insyte.activities.ProfileActivity;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.model.User;
import com.insyte.networks.ParserUtils;
import com.insyte.utils.Initialize;
import com.insyte.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class SettingFragment extends Fragment {
    SeekBar seek_bar_distance, seek_bar_interest_level;
    TextView tv_radar_range, tv_level;
    Button btn_Done;
    Switch toggle_visible;
    ImageView imgBack;
    float fToggleW = 157;
    float fToggleH = 52;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    int progress = 0;
    int distance = 0, level = 0;
    boolean isVisible = false;
    private String url_save_setting = Constants.URL_API + "/settings/%s?token=%s";
    private String url_get_setting = Constants.URL_API + "/settings/%s?token=%s";
    private Initialize initialize;
    private ProgressDialog progressDialog;
    private User user;
    private Map<String, Object> params;
    AQuery aQuery;
    View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefs = getActivity().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
        editor = prefs.edit();
        aQuery = new AQuery(getActivity());
        editor = prefs.edit();
        params = new HashMap<String, Object>();
        initialize = new Initialize(getActivity());
        progressDialog = initialize.createProgressDialog("Loading");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_setting, container, false);
        getViewController();
        getUserSetting();
        return view;
    }

    private void getUserSetting() {
        String url_setting = String.format(url_get_setting, InsyteApp.getInstance().getUser().getId(), InsyteApp.getInstance().getUser().getToken());
        aQuery.ajax(url_setting, JSONObject.class, new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject json, AjaxStatus status) {
                        super.callback(url, json, status);
                        if (json != null) {
                            try {
                                if (json.has("code")) {
                                    if (json.getInt("code") == 1) {
                                        parerUserSetting(json);
                                        // ToastUtils.showToast(SettingActivity.this, "save success");
                                    } else if (json.getInt("code") == -100) {
                                        ToastUtils.showToast(getActivity(), "error");
                                    } else if (json.getInt("code") == 4) {
                                        ToastUtils.showToast(getActivity(), "bad request");
                                    }
                                }
                            } catch (Exception e) {
                                ToastUtils.showToast(getActivity(), "error. please check it again");
                            }
                        } else ToastUtils.showToast(getActivity(), "Check your network");
                    }
                }

        );
    }

    private void getViewController() {
        seek_bar_distance = (SeekBar) view.findViewById(R.id.seek_bar_distance);
        seek_bar_interest_level = (SeekBar) view.findViewById(R.id.seek_bar_interest_level);
        toggle_visible = (Switch) view.findViewById(R.id.toggle_visible);
        toggle_visible.getLayoutParams().width = (int) (fToggleW * Constants.fScale);
        toggle_visible.getLayoutParams().height = (int) (fToggleH * Constants.fScale);
        tv_radar_range = (TextView) view.findViewById(R.id.tv_radar_range);
        toggle_visible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isVisible = true;
                    toggle_visible.setBackgroundResource(R.drawable.ic_on);
                    //ToastUtils.showToast(SettingActivity.this, "visible");
                } else {
                    isVisible = false;
                    toggle_visible.setBackgroundResource(R.drawable.ic_off);
                    //ToastUtils.showToast(SettingActivity.this, "NOT Visible");
                }
                // do something, the isChecked will be
                // true if the switch is in the On position
            }
        });
        imgBack = (ImageView) view.findViewById(R.id.imgBack);
        tv_level = (TextView) view.findViewById(R.id.tv_level);
        btn_Done = (Button) view.findViewById(R.id.btn_Done);
//        imgBack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(getActivity(), ProfileActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
//            }
//        });
        btn_Done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveUserSettingToServer();
                saveUserSettingLocal();
            }
        });
        seek_bar_distance.setMax(100);
        seek_bar_distance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
                progress = progresValue;
                tv_radar_range.setText(progress + " miles");
                //Toast.makeText(getApplicationContext(), "Changing seekbar's progress", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tv_radar_range.setText(progress + " miles");
                distance = progress;
                //Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
            }
        });
        seek_bar_interest_level.setMax(10);
        seek_bar_interest_level.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressLevel = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
                progressLevel = progresValue;
                tv_level.setText(progressLevel + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tv_level.setText(progressLevel + "");
                level = progressLevel;
                //Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void saveUserSettingLocal() {
        editor.putInt(Constants.KEY_USER_DISTANCE, distance);
        editor.putInt(Constants.KEY_USER_LEVEL, level);
        editor.putBoolean(Constants.KEY_USER_VISIBLE, isVisible);
        editor.commit();
    }

    public void saveUserSettingToServer() {
        String url_setting = String.format(url_save_setting, InsyteApp.getInstance().getUser().getId(), InsyteApp.getInstance().getUser().getToken());
        params.put("visibility", isVisible ? 1 : 0);
        params.put("distance", distance);
//        params.put("interests_level", level);
        params.put("interests_level", 0);
        aQuery.ajax(url_setting, params, JSONObject.class, new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject json, AjaxStatus status) {
                        super.callback(url, json, status);
                        if (json != null) {
                            try {
                                if (json.has("code")) {
                                    if (json.getInt("code") == 1) {
                                        ToastUtils.showToast(getActivity(), "save success");
                                    } else if (json.getInt("code") == -100) {
                                        ToastUtils.showToast(getActivity(), "error");
                                    } else if (json.getInt("code") == 4) {
                                        ToastUtils.showToast(getActivity(), "bad request");
                                    }
                                }
                            } catch (Exception e) {
                                ToastUtils.showToast(getActivity(), "error. please check it again");
                            }
                        } else ToastUtils.showToast(getActivity(), "Check your network");
                    }
                }.method(AQuery.METHOD_PUT)

        );
    }

    public void parerUserSetting(JSONObject jsonObject) {
        try {
            JSONObject objData = ParserUtils.getJsonObject(jsonObject, "data");
            int visible = ParserUtils.getIntValue(objData, "visibility");
            distance = ParserUtils.getIntValue(objData, "distance");
            level = ParserUtils.getIntValue(objData, "interests_level");
            if (visible == 1) isVisible = true;
            else isVisible = false;
            if (isVisible) toggle_visible.setBackgroundResource(R.drawable.ic_on);
            else toggle_visible.setBackgroundResource(R.drawable.ic_off);
            tv_radar_range.setText(distance + " miles");
            seek_bar_distance.setProgress(distance);
            tv_level.setText(level + "");
            seek_bar_interest_level.setProgress(level);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
